package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UserController {
    //获取header里面的信息 @RequestHeader
    @RequestMapping("/getHeader")
    public  Object getHeader(@RequestHeader("User-Agent") String status){
        return "status:"+status;
    }
    private  static  final   String SESSION_KEY="key";
    //存储sesssion
    @RequestMapping("/setSession")
    //利用servlet设置session
   public  void setSessionKey(HttpServletRequest req){
       HttpSession httpSession=req.getSession();
       httpSession.setAttribute(SESSION_KEY,"zhangsan");
   }
    //获取session @SessionAttribute()
   @RequestMapping("/getSession")
   public  Object getSessionKey(@SessionAttribute(SESSION_KEY) String name){
       return "name"+name;
   }
   //获取cookie @CookieValue
    @RequestMapping("/getCookie")
    public  Object getCookie(@CookieValue(value = "hello") String name){
        return name;

    }
   //path(url) /getpara3/{name}/{pwd} (@PathVariable
    @RequestMapping("/getpara3/{name}/{pwd}")
    public Object getpara3(@PathVariable String name, @PathVariable(name = "pwd") String pssword){
        return "name: "+name+"  password:"+pssword;

    }

      @RequestMapping("/getpara2")
    public Object getpara2(@RequestParam(value = "username") String name){
        return "name:"+name;
    }
   //传参数
    @RequestMapping("/getpara1")
    //不传递name参数默认是null
    public Object getpara1(String name,String password){
        return "name:"+name+" password:"+password;
    }
//利用servlet获取请求中的参数
    @RequestMapping("/getpara")
    public  Object getpara(HttpServletRequest req, HttpServletResponse res){
        return "req: "+req.getParameter("name");
    }
    //获取对象
    @RequestMapping("/getpara4")
    public Object getpara4(User user){
        System.out.println(user);
        return user;
    }
    //获取json对象
    @RequestMapping("/getpara5")
    public Object getpara5(@RequestBody User user){
        System.out.println("getpara5");
        return user;
    }
    //文件传输
    public Object upload(@RequestPart("1")MultipartFile file){
        String fileName= UUID.randomUUID()+
                         file.getOriginalFilename().substring(
                                 file.getOriginalFilename().lastIndexOf(".")//后缀名
                         );
        File saveFie=new File("D:\\Data\\"+fileName);
        try {
            file.transferTo(saveFie);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  false;
    }
    @RequestMapping("/hello")
    public  String sayhello(){
        return "hello word";
    }

}
